package com.common;

import com.github.dozermapper.core.DozerBeanMapperBuilder;
import com.github.dozermapper.core.Mapper;
import com.google.common.collect.Lists;

import java.util.Collection;
import java.util.List;

/**
 * 基于Dozer 6.4.1简单封装,, 实现深度转换Bean<->Bean的Mapper.实现: 1. 持有Mapper的单例. 2. 返回值类型转换. 3.
 * 批量转换Collection中的所有对象. 4. 区分创建新的B对象与将对象A值复制到已存在的B对象两种函数.
 */
public class BeanMapper {

    /**
     * 持有Dozer单例, 避免重复创建DozerMapper消耗资源.
     */
    private static Mapper mapper = DozerBeanMapperBuilder.buildDefault();

    /**
     * 基于Dozer转换对象的类型.
     */
    public static <T> T map(Object source, Class<T> destinationClass) {
        if (source == null) {
            return null;
        }
        return mapper.map(source, destinationClass);
    }

    /**
     * 基于Dozer转换Collection中对象的类型.
     */
    public static <T> List<T> mapList(Collection<?> sourceList, Class<T> destinationClass) {
        if (sourceList == null) {
            return null;
        }
        List<T> destinationList = Lists.newArrayList();
        for (Object source : sourceList) {
            T destinationObject = mapper.map(source, destinationClass);
            destinationList.add(destinationObject);
        }
        return destinationList;
    }

    /**
     * 基于Dozer将对象A的值拷贝到对象B中.
     */
    public static void copy(Object source, Object destinationObject) {
        mapper.map(source, destinationObject);
    }
}

